//
//  UnitEditController.m
//  MapEdit
//
//  Created by Steven Canfield on 6/27/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "UnitEditController.h"


@implementation UnitEditController

- (Unit *)currentUnit {
	if( [selectedUnits count] == 1 ) {
		return [selectedUnits lastObject];
	} else if( [selectedUnits count] > 1 ) {
		return NULL;
	} else {
		return NULL;
	}
}

- (void)awakeFromNib { 
	selectedUnits = [[NSMutableArray alloc] init];
	NSMenu * unitTypeMenu = [unitTypeButton menu];
	/* Empty Menu */
	while( [unitTypeMenu numberOfItems] != 0 ) {
		[unitTypeMenu removeItemAtIndex:[unitTypeMenu numberOfItems]-1];
	}
	
	int unitIndex = 0;
	while( unitIndex < 228 ) {
		NSMenuItem * item = [[NSMenuItem alloc] initWithTitle:[[Unit unitNames] objectAtIndex:unitIndex] action:@selector(updateControl:) keyEquivalent:@""];
		[item setEnabled:YES];
		[item setTarget:self];
		[unitTypeMenu addItem: item ];
		unitIndex++;
	}
	
			
	[unitTypeMenu setAutoenablesItems:NO];
	[unitTypeMenu setDelegate:self];
	
	NSMenu * unitOwnerMenu = [unitOwnerButton menu];
	int ownerIndex = 0;
	while( ownerIndex < 8 ) {
		NSMenuItem * item = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"%i", ownerIndex] action:@selector(updateControl:) keyEquivalent:@""];
		[item setAttributedTitle:[[NSArray coloredTeamNames] objectAtIndex: ownerIndex ]];
		[item setEnabled:YES];
		[item setTarget:self];
		[unitOwnerMenu addItem: item ];
		ownerIndex++;
	}
	[unitOwnerMenu setAutoenablesItems:NO];
	[unitOwnerMenu setDelegate:self];

	
	allItems = [[NSArray arrayWithObjects: unitTypeButton, unitOwnerButton, coordinateX, coordinateY, healthSlider,
	healthField, shieldSlider, shieldField, energySlider, energyField, resourceField,
	cloakedBox, hallucinatedBox, burrowedBox, invincibleBox, NULL] retain];
	
	[self updateEditPanel];
}

- (BOOL)validateMenuItem:(NSMenuItem *)menuItem {
	return YES;
}

- (BOOL)containsUnit:(Unit *)unit {
	return [selectedUnits containsObject:unit];
}

- (void)addUnit:(Unit *)unit {
	[self willChangeValueForKey:@"currentUnit"];
	[selectedUnits addObject:unit];
	[self didChangeValueForKey:@"currentUnit"];
	//[self updateEditPanel];
	
}

- (void)clearSelection {
	[self willChangeValueForKey:@"currentUnit"];
	[selectedUnits release];
	selectedUnits = [[NSMutableArray alloc] init];
//	[self updateEditPanel];
	[self didChangeValueForKey:@"currentUnit"];
}

- (Unit *)unitAtIndex:(NSInteger)index {
	return [selectedUnits objectAtIndex:index];
}

- (void)removeUnit:(Unit *)unit {
	[selectedUnits removeObject:unit];
}

- (void)removeUnitAtIndex:(NSInteger)index {
	[selectedUnits removeObjectAtIndex:index];
}

- (void)updateEditPanel {
	if( [selectedUnits count] == 1 ) {
		if( disabled ) {
		for( NSControl * control in allItems ) {
			[self enableControl:control];
			disabled = NO;
		}
	}
	
	Unit * unit = [selectedUnits objectAtIndex:0];
	
	[unitTypeButton selectItemWithTitle:[NSString stringWithFormat:@"%i", [unit type]]];
	[unitOwnerButton selectItemWithTitle:[NSString stringWithFormat:@"%i", [unit owner]]];
	
	[coordinateX setIntValue:[ unit location ].x ];
	[coordinateY setIntValue:[ unit location ].y ];
	
	//[self updateSlider:healthSlider withField:healthField object:unit selector:@selector(health)];
	[self updateControl:energySlider fromObject:unit forProperty:@"energy"];
//	[self updateSlider:energySlider withField:energyField object:unit selector:@selector(energy)];
	[self updateSlider:shieldSlider withField:shieldField object:unit selector:@selector(shield)];
	
	/* Change resource name */
	switch( [unit type] ) {
		case 176:
		case 177:
		case 178:
			[resourceLabel setStringValue:@"Minerals:"];
			break;
		case 188:
			[resourceLabel setStringValue:@"Gas:"];
			break;
		default:
			[resourceLabel setStringValue:@"Resources:"];
			break;
	}
	[resourceField setIntValue:[ unit resource ]];
	
	
	[cloakedBox setIntValue:[ unit cloaked ]];
	[hallucinatedBox setIntValue:[ unit hallucinated ]];
	[burrowedBox setIntValue:[ unit burrowed ]];
	[invincibleBox setIntValue:[ unit invincible ]];
			
	} else if( [selectedUnits count] > 1 ) {
		// Multiple Selection
	} else {
		for( NSControl * control in allItems ) {
			[self disableControl:control];
		}
		disabled = YES;
		// No Selection
	}
}

- (void)updateControl:(NSControl *)control fromObject:(id)someObject forProperty:(NSString * )propertyName {
	/* Check to see if the stat is valid */
	SEL isValid = NSSelectorFromString([propertyName stringByAppendingString:@"Valid"]);
	
	BOOL shouldEnable = YES; // Want to enable by default
	if( [someObject respondsToSelector: isValid ] ) {
		shouldEnable = [someObject performSelector: isValid ] != 0;
	}
	
	if( shouldEnable == NO ) {
		[control setEnabled:NO];
	} else {
		[control setEnabled:YES];
		SEL valueSelector = NSSelectorFromString(propertyName);
		int value = (int)[ someObject performSelector: valueSelector ];
		
		[control setIntValue: value ];
		
	if( [control isKindOfClass:[ NSSlider class]] ) {
		SEL maxValue = NSSelectorFromString([@"max" stringByAppendingString:[propertyName capitalizedString]]);
		int max = (int)[ someObject performSelector: maxValue  ];
		id slider = [self valueForKey:[propertyName stringByAppendingString:@"Field"]];
		[(NSSlider*)control setMaxValue: max ];
		[slider setIntValue: value ];
		}
	}
}

- (void)updateSlider:(NSSlider *)slider withField:(NSTextField *)field object:(id)someObject selector:(SEL)selector {
	NSString * sel = NSStringFromSelector( selector );
	SEL maxSel = NSSelectorFromString( [@"max" stringByAppendingString:[sel capitalizedString]] );
	int max = (int)[ someObject performSelector: maxSel  ];
	int value = (int)[ someObject performSelector: selector  ];
	[slider setMaxValue: max ];
	[slider setIntValue: value ];
	[field setIntValue: value];
}

- (IBAction)updateControl:(id)sender {
/*
	NSLog([sender description] );
	Unit * unit = [selectedUnits objectAtIndex:0];
	NSPoint location = [unit location];
	if( sender == healthSlider ) {
		[unit setHealth:[healthSlider intValue]];
	} else if( sender == shieldSlider ) {
		[unit setShield:[shieldSlider intValue]];
	} else if( sender == energySlider ) {
		[unit setEnergy:[energySlider intValue]];
	} else if( sender == resourceField ) {
		[unit setResource:[resourceField intValue]];
	} else if( sender == cloakedBox ) {
		[unit setCloaked: [cloakedBox intValue ]];
	} else if( sender == hallucinatedBox ) {
		[unit setHallucinated: [hallucinatedBox intValue ]];
	} else if( sender == burrowedBox ) {
		[unit setBurrowed: [burrowedBox intValue ]];
	} else if( sender == invincibleBox ) {
		[unit setInvincible: [invincibleBox intValue ]];
	} else if( sender == coordinateX ) {
		[unit setLocation: NSMakePoint( [coordinateX intValue], location.y )];
		[mapView setNeedsDisplay:YES];
	} else if( sender == coordinateY ) {
		[unit setLocation: NSMakePoint( location.x, [coordinateY intValue] )];
		[mapView setNeedsDisplay:YES];
	} else if( [sender class] == [NSMenuItem class] ) {
		if( [[unitTypeButton itemArray] containsObject: sender ] ) {
			[unit setType:[unitTypeButton indexOfSelectedItem]];
			[mapView setNeedsDisplay:YES];
		} else if( [[unitOwnerButton itemArray] containsObject:sender] ) {
			[unit setOwner:[unitOwnerButton indexOfSelectedItem]];
			[mapView setNeedsDisplay:YES];
		}
	}
	[self updateEditPanel];
	*/
}

- (void)enableControl:( NSControl *)aControl {
	[aControl setEnabled:YES];
}

- (void)disableControl:( NSControl *)aControl {
	[aControl setEnabled:NO];
	if( [aControl class] == [NSTextField class] ) {
		[aControl setStringValue:@""];
	}
}


@end
